package cn.study.server.handler;

import cn.study.message.GroupChatResponseMessage;
import cn.study.message.GroupCreateRequestMessage;
import cn.study.server.session.Group;
import cn.study.server.session.GroupSession;
import cn.study.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @Author Zsz
 * @Date 2022/4/4 22:00
 * @Version 1.0
 **/
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null) {
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupChatResponseMessage(true, "你已经被拉入群聊" + groupName));
            }
            channelHandlerContext.channel().writeAndFlush(new GroupChatResponseMessage(true, "创建成功！"));

        } else {
            channelHandlerContext.channel().writeAndFlush(new GroupChatResponseMessage(false, "创建失败，群已存在！"));
        }

    }
}
